package com.geekaca.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geekaca.web.pojo.Brand;
import com.geekaca.web.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/SelectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用Service查询
        String pageNo = request.getParameter("pageNo");
        String cntPerPage = request.getParameter("cntPerPage");

        ServletInputStream inputStream = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));

        String line = br.readLine();
        Brand brand = JSON.parseObject(line, Brand.class);


        if (pageNo == null) {
            pageNo = "1";
        }
        if (cntPerPage == null) {
            cntPerPage = "10";
        }

        int pNO = Integer.parseInt(pageNo);
        int pageSize = Integer.parseInt(cntPerPage);

        List<Brand> allBrands = brandService.selectAll(brand,pNO, pageSize);
        // 查询条数
        Integer allBrandsCount = brandService.getAllBrandsCount(brand,pNO, pageSize);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cnt", allBrandsCount);
        jsonObject.put("brands", allBrands);


        //2. 将集合转换为JSON数据   序列化
        String jsonString = JSON.toJSONString(jsonObject);

        //3. 直接返回给数据
       /* response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();*/

        //3.1 result 返回
//        Result result = new Result();
        /*if (allBrands != null) {
            result.setCode(200);
            result.setMsg("查询成功");
        } else {
            result.setCode(500);
            result.setMsg("查询异常");
        }*/
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}